/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gmovil_jpa.DAO;

import gmovil_jpa.controladores.FacturaJpaController;
import javax.persistence.EntityManager;
import javax.persistence.Query;

/**
 *
 * @author castlerock
 */
public class DAOFactura extends FacturaJpaController {

    public Integer getProximoConsecutivo() throws Exception {
        EntityManager em = null;
        Integer proximoConsecutivo = 0;

        try {

            em = getEntityManager();
            em.getTransaction().begin();
            Query q = em.createQuery("SELECT MAX(f.consecutivo) FROM Factura f ");
            Integer c = 0;

            try {
                if (q.getSingleResult() != null) {
                    c = Integer.parseInt((String) q.getSingleResult());
                }
            } catch (NumberFormatException numberFormatException) {
                //
            }
            
            
            proximoConsecutivo =  c + 1;
            em.getTransaction().commit();
            return proximoConsecutivo;

        } catch (Exception ex) {
            //em.getTransaction().rollback();
            //ex.printStackTrace();
            throw new Exception("Imposible encontrar consecutivo.");
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }
}
